"""
2022  B圈新版课程 | 邢不行
author: 邢不行
微信: xbx6660
"""
import time

import pandas as pd
from 中性策略实盘.utils.commons import retry_wrapper


# ===获取U本位合约账户净值(不包含未实现盈亏)
def get_position_equity(exchange):
    # 账户信息V2 (USER_DATA)
    # GET /fapi/v2/account (HMAC SHA256)
    equity = retry_wrapper(exchange.fapiPrivate_get_account, func_name='fapiPrivate_get_account')
    equity = pd.DataFrame(equity['assets'])
    equity = float(equity[equity['asset'] == 'USDT']['walletBalance'])
    print('账户金额:', equity)
    if equity <= 0:
        print('账户USDT金额小于等于0，无法进行交易，退出程序')
        exit()
    return equity


# 获取用户的实际持仓
def get_position_df(exchange):
    """
    获取用户的实际持仓

              当前持仓量   均价    持仓盈亏
    symbol
    RUNEUSDT    -82.0   1.208  -0.328000
    FTMUSDT      523.0  0.189   1.208156
    """
    # 获取原始数据
    # GET /fapi/v2/positionRisk (HMAC SHA256)
    position_df = retry_wrapper(exchange.fapiPrivate_get_positionrisk, func_name='fapiPrivate_get_positionrisk')
    position_df = pd.DataFrame(position_df)

    # 整理数据
    columns = {'positionAmt': '当前持仓量', 'entryPrice': '均价', 'unRealizedProfit': '持仓盈亏'}
    position_df.rename(columns=columns, inplace=True)
    position_df = position_df[position_df['当前持仓量'] != 0]  # 只保留有仓位的币种
    position_df.set_index('symbol', inplace=True)  # 将symbol设置为index
    position_df['当前持仓量'] = position_df['当前持仓量'].astype(float)
    position_df['均价'] = position_df['均价'].astype(float)
    position_df['持仓盈亏'] = position_df['持仓盈亏'].astype(float)

    # 保留指定字段
    position_df = position_df[['当前持仓量', '均价', '持仓盈亏']]

    return position_df
